using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Winter.BackEnd.Models.Domain;
using System.Web.UI;
using System.Web.Mvc.Html;
using Winter.BackEnd.Models.Utils;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.Security;

namespace Winter.BackEnd.Controllers
{
    [Authorize]
    public class GroupController : ApplicationController
    {

        #region ActionMethods

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public ActionResult Index()
        {

            if (Roles.IsUserInRole(UserRoles.Student.RoleName))
            {
                return GetSchedule(Repository.CurrentUser.Person.Students.First().GroupID);
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public JsonResult GetScheduleForGroup(int? id)
        {
            var result = new JsonResult();
            if (id.HasValue)
            {
                int classesNumber = 6;
                var group = Repository.GetGroupByID(id.Value);

                result.Data = new
                {
                    TimeSpaces = new List<string>()
                    {
                        "8:30 - 10:05",
                        "10:25 - 12:00",
                        "12:20 - 13:55",
                        "14:15 - 15:50",
                        "16:10 - 17:45",
                        "18:05 - 19:40",
                        "20:00 - 21:35",
                    },
                    ClassesAtMonday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Monday, classesNumber),
                    ClassesAtTuesday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Tuesday, classesNumber),
                    ClassesAtWednesday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Wednesday, classesNumber),
                    ClassesAtThursday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Thursday, classesNumber),
                    ClassesAtFriday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Friday, classesNumber),
                    ClassesAtSaturday = Repository.GetGroupClassesForSpecificDayInJSON(id.Value,
                                            System.DayOfWeek.Saturday, classesNumber)
                };
            }
            return result;
        }
        public JsonResult SaveClass(string id, int subjectID, int teacherID, int buildingID, string room, int groupID)
        {
            string[] parameters = id.Split('_');
            System.DayOfWeek day = Enums.Get<System.DayOfWeek>().SingleOrDefault(en => en.ToString().ToLower() == parameters[0].ToLower());
            Class editingClass = null;
            if ((editingClass = Repository.CurrentDataContext.Classes.SingleOrDefault(c => c.ID == int.Parse(parameters[1]))) == null)
            {
                editingClass = new Class();
                Repository.CurrentDataContext.Classes.InsertOnSubmit(editingClass);
            }
            editingClass.LetureRoom = room;
            editingClass.TeacherID = teacherID;
            editingClass.SubjectID = subjectID;
            editingClass.BuildingID = buildingID;
            editingClass.ClassNumber = int.Parse(parameters[2]);
            editingClass.WorkDay = new WorkDay() { IsFirstWeek = true, DayOfWeekID = (int)day, ScheduleID = Repository.GetGroupByID(groupID).Schedules.First().ID };
            try
            {
                Repository.CurrentDataContext.SubmitChanges();
            }
            catch (Exception ex)
            {
                return new JsonResult() { Data = new { success = false } };
            }
            return new JsonResult() { Data = new { success = true } };
        }
        public JsonResult GetDataFroCreatingSchedule()
        {
            var result = new JsonResult();
            result.Data = new
            {
                Subjects = from subject in Repository.CurrentDataContext.Subjects
                           select new { Name = subject.Name, ID = subject.ID },
                Buildings = from building in Repository.CurrentDataContext.Builgings
                            select new { Name = building.BuildingName, ID = building.ID },
                Teachers = from teacher in Repository.CurrentDataContext.Teachers
                           select new { Name = teacher.FullName, ID = teacher.ID }

            };
            return result;
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Details()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Create()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();
            ViewData["Days"] = Repository.GetAllDayOfWeekForDropDown();
            ViewData["Subjects"] = Repository.GetAllSubjectsForDropDown();
            ViewData["Teachers"] = Repository.GetAllTeachersForDropDown();

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "admin")]
        public ActionResult Create(string[] Groups, string[] Days, string[] Subjects, string[] Teachers, string[] IsFirstWeek, string LectureRoom, string SubjectOrder)
        {
            var wday = Repository.CurrentDataContext.WorkDays.SingleOrDefault(wd => wd.DayOfWeekID == int.Parse(Days[0]) &&
                wd.IsFirstWeek == (IsFirstWeek[0] != "1"));
            Schedule schedule = null;
            if (Repository.CurrentDataContext.Schedules.Any(s => s.GroupID == int.Parse(Groups[0])))
            {
                schedule = Repository.CurrentDataContext.Schedules.Single(s => s.GroupID == int.Parse(Groups[0]));
            }
            else
            {
                wday.Schedule = (schedule = new Schedule() { GroupID = int.Parse(Groups[0]), Year = DateTime.Now });
            }
            schedule.WorkDays.Add(wday);
            Class scheduleForSave;
            if (!wday.Classes.Any(c => c.ClassNumber == int.Parse(SubjectOrder)))
            {
                scheduleForSave = new Class()
                {
                    SubjectID = int.Parse(Subjects[0]),
                    TeacherID = int.Parse(Teachers[0]),
                    ClassNumber = int.Parse(SubjectOrder)

                };
            }
            else
            {
                scheduleForSave = wday.Classes.Single(c => c.ClassNumber == int.Parse(SubjectOrder));
            }
            wday.Classes.Add(scheduleForSave);

            Repository.CurrentDataContext.SubmitChanges();

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();
            ViewData["Days"] = Repository.GetAllDayOfWeekForDropDown();
            ViewData["Subjects"] = Repository.GetAllSubjectsForDropDown();
            ViewData["Teachers"] = Repository.GetAllTeachersForDropDown();

            //ViewData["sch"] = GetSchedule(Groups);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetShortSubjectDetails(string ID)
        {
            var result = new JsonResult();
            if (!string.IsNullOrEmpty(ID) && Repository.CurrentDataContext.Classes.Any(c => c.ID == int.Parse(ID)))
            {
                Class ClassByID = Repository.CurrentDataContext.Classes.SingleOrDefault(c => c.ID == int.Parse(ID));

                result.Data = new
                {
                    Name = ClassByID.Subject.Name,
                    ClassStartTime = FormatTime(ClassByID.ClassStartTime),
                    ClassEndTime = FormatTime(ClassByID.ClassEndTime),
                    Teacher = ClassByID.Teacher != null ? ClassByID.Teacher.Person.LastName : "",
                    Building = ClassByID.Builging.BuildingName,
                    LetureRoom = ClassByID.LetureRoom
                };
                return result;
            }

            result.Data = new { };
            return result;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetSchedules()
        {
            var page = new { page = 1 };

            var rows = (from sch in Repository.CurrentDataContext.Schedules
                        select new
                        {
                            id = sch.ID,
                            cell = new[] { 
                                sch.ID.ToString(), 
                                sch.Group.Department.Faculty.Name,
                                sch.Group.Department.Name,
                                sch.Group.Name, 
                                DateTime.Now.Year.ToString() 
                            }
                        }).ToList();

            var result = new JsonResult();
            result.Data = new { page = 1, records = rows.Count(), rows, total = 1 };

            return result;
        }

        #endregion

        #region HelperMethods

        private string FormatTime(TimeSpan time)
        {
            return string.Format("{0}:{1:D2}", time.Hours, time.Minutes);
        }

        private string GetActionLinkForClass(int classNumber, int groupID, System.DayOfWeek day)
        {
            if (Repository.CurrentDataContext.Classes.Any(c => c.ClassNumber == classNumber && c.WorkDay.Schedule.GroupID == groupID && c.WorkDay.DayOfWeek.ID == (int)day))
            {
                var cl = Repository.CurrentDataContext.Classes.SingleOrDefault(c => c.ClassNumber == classNumber && c.WorkDay.Schedule.GroupID == groupID && c.WorkDay.DayOfWeek.ID == (int)day);

                return "";
                //return (new AjaxHelper(),(IViewDataContainer)this).ActionLink(string.Format("{0}\n{1}\n({2})", cl.Subject.Name, cl.LetureRoom, cl.Teacher.Person.FullName),
                //    "GetSubjectDetails", cl.ID.ToString(), new System.Web.Mvc.Ajax.AjaxOptions() { UpdateTargetId = "subjectDetails", OnSuccess = "$('#dialog').dialog();" }, null));

            }
            return @"<a href=""#"">empty</a>";

        }

        private ActionResult GetSchedule(int groupID)
        {
            int classesNumber = 6;
            var group = Repository.GetGroupByID(groupID);
            ViewData["Title"] = "Schedule for group " + group.Name;

            ViewData["TimeSpaces"] = new List<string>()
                    {
                        "8:30 - 10:05",
                        "10:25 - 12:00",
                        "12:20 - 13:55",
                        "14:15 - 15:50",
                        "16:10 - 17:45",
                        "18:05 - 19:40",
                        "20:00 - 21:35",
                    };

            ViewData["ClassesAtMonday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Monday, classesNumber);
            ViewData["ClassesAtTuesday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Tuesday, classesNumber);
            ViewData["ClassesAtWednesday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Wednesday, classesNumber);
            ViewData["ClassesAtThursday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Thursday, classesNumber);
            ViewData["ClassesAtFriday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Friday, classesNumber);
            ViewData["ClassesAtSaturday"] =
                                    Repository.GetGroupClassesForSpecificDay(groupID,
                                    System.DayOfWeek.Saturday, classesNumber);
            return View();
        }

        #endregion

    }
}
